/**
 * Created by bdqn on 2016/5/3.
 */
function register() {
    //获取相关字段的值
    var loginName = $("input[name='loginName']").val();
    var userName = $("input[name='userName']").val();
    var password = $("input[name='password']").val();
    var confirmPassword = $("input[name='pwd']").val();
    var email = $("input[name='email']").val();
    var mobile = $("input[name='mobile']").val();
    var identityCode = $("input[name='identityCode']").val();
    var address = $("input[name='address']").val();
    var sex = $("input[name='sex']:checked").val();

    //判断密码是否一致
    if (loginName == null || loginName == "") {
        cocoMessage.info("用户名不能为空.");
        return;
    }

    if (loginName.length < 2 || loginName > 10) {
        cocoMessage.info("登录名不能小于两个字符或者大于十个字符.");
        return;
    }

    if (userName == null || userName == "") {
        cocoMessage.info("真实姓名不能为空.");
        return;
    }

    if (userName.length < 2 || userName > 10) {
        cocoMessage.info("真实姓名不能小于两个字符或者大于十个字符.");
        return;
    }

    if (password != confirmPassword) {
        cocoMessage.info("两次输入的密码不一致.");
        return;
    }
    //判断密码是否为空
    if (password == "") {
        cocoMessage.info("密码不能为空");
        return;
    }
    //验证邮箱格式
    if (email != null && email != "" && !checkMail(email)) {
        cocoMessage.info("邮箱格式不正确");
        return;
    }
    //验证邮箱格式
    if (mobile != null && mobile != "" && !checkMobile(mobile)) {
        cocoMessage.info("手机格式不正确");
        return;
    }
    //验证邮箱格式
    if (identityCode != null && identityCode != "" && !checkIdentityCode(identityCode)) {
        cocoMessage.info("身份证号格式不正确");
        return;
    }

    $.ajax({
        url: "user/registered",
        method: "post",
        data: {
            loginName: loginName,
            userName: userName,
            password: password,
            sex: sex,
            email: email,
            mobile: mobile,
            identityCode: identityCode,
            address: address
        },
        dataType: "json",//ajax接口（请求url）返回的数据类型
        success: function (jsonStr) {

            if (jsonStr.status == 1) {
                cocoMessage.info(jsonStr.message);
                window.location.href = "user/login";
            } else {
                cocoMessage.info(jsonStr.message);
            }
        }
    })
}


function checkMail(mail) {
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (filter.test(mail))
        return true;
    else {
        return false;
    }
}

function checkMobile(phone) {
    var filter = /^\d{5,11}$/;
    if (filter.test(phone))
        return true;
    else {
        return false;
    }
}

function checkIdentityCode(identityCode) {
    var filter = /^\w{18}$/;
    if (filter.test(identityCode))
        return true;
    else {
        return false;
    }
}

function addUser() {

    //获取相关字段的值
    var id = $("input[name='id']").val();
    var loginName = $("input[name='loginName']").val();
    var userName = $("input[name='userName']").val();
    var password = $("input[name='password']").val();
    var confirmPassword = $("input[name='pwd']").val();
    var email = $("input[name='email']").val();
    var mobile = $("input[name='mobile']").val();
    var identityCode = $("input[name='identityCode']").val();
    var address = $("input[name='address']").val();
    var sex = $("input[name='sex']:checked").val();
    var type = $("select[name='type']").val();

    //判断密码是否一致
    if (loginName == null || loginName == "") {
        cocoMessage.info("用户名不能为空.");
        return;
    }

    if (loginName.length < 2 || loginName > 10) {
        cocoMessage.info("登录名不能小于两个字符或者大于十个字符.");
        return;
    }

    if (userName == null || userName == "") {
        cocoMessage.info("真实姓名不能为空.");
        return;
    }

    if (userName.length < 2 || userName > 10) {
        cocoMessage.info("真实姓名不能小于两个字符或者大于十个字符.");
        return;
    }

    if (password != confirmPassword) {
        cocoMessage.info("两次输入的密码不一致.");
        return;
    }
    //判断密码是否为空
    if (password == "") {
        cocoMessage.info("密码不能为空");
        return;
    }
    //验证邮箱格式
    if (email != null && email != "" && !checkMail(email)) {
        cocoMessage.info("邮箱格式不正确");
        return;
    }
    //验证邮箱格式
    if (mobile != null && mobile != "" && !checkMobile(mobile)) {
        cocoMessage.info("手机格式不正确");
        return;
    }
    //验证邮箱格式
    if (identityCode != null && identityCode != "" && !checkIdentityCode(identityCode)) {
        cocoMessage.info("身份证号格式不正确");
        return;
    }

    var uri = "addUser";

    //判断密码为空时，说明是修改
    if (password == null) {
        uri = "updateUser"
    }

    $.ajax({
        url: "user/" + uri,
        method: "post",
        data: {
            id: id,
            loginName: loginName,
            userName: userName,
            password: password,
            sex: sex,
            email: email,
            mobile: mobile,
            identityCode: identityCode,
            address: address,
            type: type
        },
        dataType: "json",//ajax接口（请求url）返回的数据类型
        success: function (jsonStr) {

            if (jsonStr.status == 1) {
                cocoMessage.info(jsonStr.message);
                window.setTimeout("window.location='user/memberCollect?action=memberCollect&current=1'", 1000);

            } else {
                cocoMessage.info(jsonStr.message);
            }
        }
    })
}

/**
 * 删除方法
 * @param id
 */
function deleteUserId(id) {

    if (confirm("确定删除此用户信息么？") == true) {

        $.ajax({
            url: "user/deleteUserById",
            method: "post",
            data: {
                id: id
            },
            dataType: "json",//ajax接口（请求url）返回的数据类型
            success: function (jsonStr) {

                if (jsonStr.status == 1) {
                    cocoMessage.info(jsonStr.message);
                    window.setTimeout("window.location='user/memberCollect?action=memberCollect&current=1'", 1000);

                } else {
                    cocoMessage.info(jsonStr.message);
                }
            }
        })
    }


}

// var script = document.createElement('script');
// script.src = "static/js/jquery-1.8.2.min.js";
// document.head.appendChild(script);

/**
 * 选择分类时
 * @param obj
 */
function selectProductCategoryLevel(obj, alerts) {

    //获取类型
    var type = obj.value;

    $.ajax({
        url: "category/selectProductCategory",
        data: {
            type: type
        },
        method: "post",
        dataType: "json",
        success: function (data) {

            if (data.status == 1) {

                if (type == 2) {

                    $("#leve1").css("display", "");
                    $("#leve2").css("display", "none");
                    //调用了渲染方法
                    lists(data, alerts)


                } else if (type == 3) {

                    $("#leve1").css("display", "");
                    $("#leve2").css("display", "");

                    //调用了渲染方法
                    lists(data, alerts)

                } else {
                    $("#leve1").css("display", "none");
                    $("#leve2").css("display", "none");
                }


            }

        }


    })

}


/**
 * 二级分类
 * @param obj
 * @param str
 */
function queryProductCategoryList(obj, alerts) {

    var id = obj.value;

    $.ajax({
        url: "category/selectProductCategoryLeve2",
        data: {
            id: id
        },
        method: "post",
        dataType: "json",
        success: function (data) {

            if (data.status == 1) {

                //调用了渲染方法
                lists(data, alerts)

            }

        }
    })

}

//修改
function addOrUpdate() {
    var id = $("#ids").val();
    if (id == null || id == "") {
        saveOrUpdate();
    } else {
        modifyProductCategory();
    }
}

/**
 * 修改分类方法
 */
function modifyProductCategory() {
    var id = $("#ids").val();
    var productCategoryLevel1 = $("#productCategoryLevel1").val();
    var productCategoryLevel2 = $("#productCategoryLevel2").val();
    var name = $("#name").val();
    var type = $("#type").val();

    if (RequiredFieldValidatorMethod(id, name, type, productCategoryLevel1, productCategoryLevel2)) {

        $.ajax({
            url: "category/productCategory",
            method: "post",
            data: {
                id: id,
                name: name,
                type: type,
                productCategoryLevel1: (productCategoryLevel1 == null || productCategoryLevel1 == "") ? 0 : productCategoryLevel1,
                productCategoryLevel2: (productCategoryLevel2 == null || productCategoryLevel2 == "") ? 0 : productCategoryLevel2
            },
            success: function (result) {
                //状态判断
                if (result.status == 1) {

                    cocoMessage.info(result.message);

                    setTimeout(function () {
                        history.go(0);
                    }, 1000);

                } else {

                    cocoMessage.info(result.message);


                }
            }
        });
    }
};

/**
 * 非空验证分类管理（修改）
 * @constructor
 */
function RequiredFieldValidatorMethod(id, name, type, productCategoryLevel1, productCategoryLevel2) {


    console.log(id, name, type, productCategoryLevel1, productCategoryLevel2);

    if (type == 0) {
        cocoMessage.info("分类级别不能为空！")
    } else if (name == '' || name == null) {
        cocoMessage.info("分类名称不能为空！")
    } else if (id == 0) {
        cocoMessage.info("分类id不能为空！")
    } else if (type == 2 && productCategoryLevel1 == 0) {
        cocoMessage.info("一级分类不能为空！")
    } else if (type == 3) {

        if (productCategoryLevel1 == 0) {
            cocoMessage.info("一级分类不能为空！")

        } else if (productCategoryLevel2 == 0) {
            cocoMessage.info("二级分类不能为空！")
        } else {

            return true;
        }

    } else {

        return true;
    }


    return false;
}

/**
 * 添加分类
 */
function saveOrUpdate() {

    //获取类型
    var type = document.getElementById("type").value;

    //获取内容
    var names = document.getElementById("name").value;
    var name = names == null || names == '' || names.length == 0 ? null : names;

    var productCategoryLevels = $("#productCategoryLevel" + (type - 1)).find("option:selected").val();
    var productCategoryLevel = productCategoryLevels == null || productCategoryLevels == '' || productCategoryLevels.length == 0 ? 0 : productCategoryLevels;

    if (type == 0) {

        cocoMessage.info("请选择分类级别");
    } else if (type == 2 && productCategoryLevel == 0) {

        cocoMessage.info("请选择一级分类级别");
    } else if (type == 3 && productCategoryLevel == 0) {

        var leve1 = $("#productCategoryLevel" + (type - 2)).find("option:selected").val();

        if (leve1 == 0) {
            cocoMessage.info("请选择一级分类级别");
        } else {
            cocoMessage.info("请选择二级分类级别");
        }

    } else if (name == null) {
        cocoMessage.info("分类名称不能为空！");
    } else if (type == 1) {

        if (name != null && name != '' && name.length > 0) {

            addProductCategory(type, productCategoryLevel, name);
        } else {
            cocoMessage.info("分类名称不能为空！");
        }

    } else {

        if (type == 2 && productCategoryLevel != 0) {

            if (name != null && name != '' && name.length > 0) {

                //添加方法
                addProductCategory(type, productCategoryLevel, name);

            } else {

                cocoMessage.info("分类名称不能为空！");
            }

        } else if (type == 3 && productCategoryLevel != 0) {

            if (productCategoryLevel - 1 != 0) {

                if (name != null && name != '' && name.length > 0) {

                    //添加方法
                    addProductCategory(type, productCategoryLevel, name);

                } else {

                    cocoMessage.info("分类名称不能为空！");

                }

            } else {
                cocoMessage.info("请选择一级分类！");

            }


        } else if (type == 3 && productCategoryLevel == 0) {
            cocoMessage.info("请选择二级分类！");

        } else {
            cocoMessage.info("请选择一级分类！");

            return;
        }


    }


}

/**
 * 添加方法
 * @param type
 * @param parentId
 * @param name
 */
function addProductCategory(type, parentId, name) {

    $.ajax({
        url: "category/addProductCategory",
        data: {
            type: type,
            parentId: parentId,
            name: name
        },
        method: "post",
        dataType: "json",
        success: function (data) {

            if (data.status == 1) {

                cocoMessage.info(data.message);
                // window.setTimeout("window.location='category/classifyManage?current=1'", 1000);
                setTimeout(function () {
                    history.go(0);
                }, 1000);
            } else {
                cocoMessage.info(data.message);

            }

        }
    })

}

/**
 * 删除分类管理
 * @param id
 */
function deleteProductCategory(id) {

    if (confirm("确定删除此分类信息么？") == true) {


        $.ajax({
            url: "category/deleteProductCategory",
            data: {
                id: id
            },
            method: "post",
            dataType: "json",
            success: function (data) {

                if (data.status == 1) {

                    cocoMessage.info(data.message);

                    // window.setTimeout("window.location='category/classifyManage?current=1'", 1000);
                    setTimeout(function () {
                        history.go(0);
                    }, 1000);

                } else {

                    cocoMessage.info(data.message);

                }

            }

        })

    }


}

/**
 * 删除商品
 * @param id
 */
function deleteById(id) {

    if (confirm("确定删除此商品信息么？") == true) {


        $.ajax({
            url: "easybuy/deleteById",
            data: {
                id: id
            },
            method: "post",
            dataType: "json",
            success: function (data) {

                if (data.status == 1) {

                    cocoMessage.info(data.message);
                    window.setTimeout("window.location='easybuy/products?current=1'", 1000);
                } else {

                    cocoMessage.info(data.message);

                }

            }

        })

    }

}


/**
 * 渲染方法
 * @param data
 * @param alerts
 */
function lists(data, alerts) {

    $("#" + alerts).empty()

    var str = "<option value='0' selected='selected'>请选择...</option>";

    $("#" + alerts).empty();

    for (var i = 0; i < data.list.length; i++) {

        str += "<option value=" + data.list[i].id + ">" + data.list[i].name + "</option>";

    }

    $("#" + alerts).append(str);

}

/**
 * 商品上架
 */
function newStock() {

    var ids = $("#id").val();//获取id
    var product1 = $("#product1").find("option:selected").val();//获取一级分类
    var product2 = $("#product2").find("option:selected").val(); //获取二级分类
    var product3 = $("#product3").find("option:selected").val();  //获取三级分类
    var name = $("#name").val();//获取商品名称
    var fileName = $("input[name='photo']").val();//获取文件名称
    var price = $("#price").val();//商品价格
    var stock = $("#stock").val();//库存
    var files = fileName.substr(fileName.indexOf(".") + 1, fileName.length); //截取文件后缀名

    var id = ids == null || ids == '' ? 0 : ids;

    if (product1 == 0) {
        cocoMessage.info("一级分类不能为空！")
    } else if (product2 == 0) {
        cocoMessage.info("二级分类不能为空！")
    } else if (product3 == 0) {
        cocoMessage.info("三级分类不能为空！")
    } else if (name == '') {
        cocoMessage.info("商品名称不能为空！")
    } else if (price == '') {
        cocoMessage.info("商品价格不能为空！")
    } else if (stock == '') {
        cocoMessage.info("库存不能为空！")
    } else if (isNaN(price)) {
        cocoMessage.info("商品价格只能是数字！")
        $("#price").val("");
    } else if (isNaN(stock)) {
        cocoMessage.info("库存只能是数字！")
        $("#stock").val('');
    } else if (price <= 0) {
        cocoMessage.info("价格不能小于0！")
    } else if (stock <= 0) {
        cocoMessage.info("库存不能小于0！")

    } else if (id == 0) {

        if (fileName == '') {
            cocoMessage.info("商品图片不能为空！")
        } else if (files != "png" && files != "gif" && files != "jpg") {
            cocoMessage.info("商品图片格式不正确，必须为（fig、png、jpg、）格式！")
        } else {
            return true;
        }

        //修改时
    } else {

        if (fileName != '') {
            if (files != "png" && files != "gif" && files != "jpg") {
                cocoMessage.info("商品图片格式不正确，必须为（fig、png、jpg、）格式！")
            } else {
                return true;
            }
        } else {
            return true;
        }
    }


    return false;
}

/**
 * 修改分类管理
 */
function toUpdateProductCategoryList(obj, type) {

    var id = $(obj).val();

    console.log(id, type)

    var types = $("#type").find("option:selected").val();

    $("#type option").each(function () {

        $(this).prop("selected", false);

    })

    //循环下拉框
    $("#type option").each(function () {

        //获取下拉框的值
        var values = $(this).val()

        if (type == values) {

            $(this).prop("selected", true);

        }


    })
    $("#type").prop("disabled", true);

    //显示
    $("#addProductCategory").css("display", "block");


    $.ajax({
        url: "category/queryProduct",
        method: "post",
        data: {
            type: type,
            id: id
        },
        dataType: "json",
        success: function (data) {

            //判断成功时
            if (data.status == 1) {

                applySelect(data)

                $("#name").val(data.category.name)
                $("#ids").val(data.category.id);
            }

        }


    })

    //显示一级分类
    if (type == 2) {

        $("#leve1").css("display", "");
        $("#leve2").css("display", "none");

        //显示一级和二级分类
    } else if (type == 3) {
        $("#leve1").css("display", "");
        $("#leve2").css("display", "");

        //隐藏所有分类
    } else {

        $("#leve1").css("display", "none");
        $("#leve2").css("display", "none");
    }


}

/**
 * 渲染方法
 * @param data
 * @param alerts
 */
function applySelect(data) {

    $("#productCategoryLevel1").empty();
    $("#productCategoryLevel1").empty();

    $("#productCategoryLevel2").empty()
    $("#productCategoryLevel2").empty();

    var str = "<option value='0' selected='selected'>请选择...</option>";
    var strs = "<option value='0' selected='selected'>请选择...</option>";

    if (data.category2 != null && data.list != null) {

        for (var i = 0; i < data.list.length; i++) {

            if (data.list[i].id == data.category2.id) {

                str += "<option value=" + data.list[i].id + " selected=true >" + data.list[i].name + "</option>";

            } else {

                str += "<option value=" + data.list[i].id + ">" + data.list[i].name + "</option>";
            }

        }
    } else {

        if (data.list != null) {

            for (var c = 0; c < data.list.length; c++) {

                if (data.list[c].id == data.category1.id) {

                    str += "<option value=" + data.list[c].id + " selected=true >" + data.list[c].name + "</option>";

                } else {

                    str += "<option value=" + data.list[c].id + ">" + data.list[c].name + "</option>";
                }

            }
        }
    }

    if (data.category1 != null && data.list2 != null) {

        for (var k = 0; k < data.list2.length; k++) {

            if (data.list2[k].id == data.category1.id) {

                strs += "<option value=" + data.list2[k].id + "  selected=true>" + data.list2[k].name + "</option>";

            } else {

                strs += "<option value=" + data.list2[k].id + ">" + data.list2[k].name + "</option>";

            }
        }

    }

    $("#productCategoryLevel1").append(str);
    $("#productCategoryLevel2").append(strs);


}